(function ($) {
    /**
     * @summary 为元素添加唯一ID
     * @name uiCore#setElemID
     * @function
     * @returns {Object}
     */
    $.fn.setElemID = function () {
        var elem = this;
        if (!this instanceof jQuery) {
            elem = $(this);
        }
        if (!elem.attr('id')) {
            elem.attr('id',guidGenerator());
        }
        return elem;
    };
    /**
     * @summary 获取元素ID
     * @name uiCore#getElemID
     * @function
     * @returns id
     */
    $.fn.getElemID = function () {
        var elem = this;
        if (!this instanceof jQuery) {
            elem = $(this);
        }
        return elem.attr('id');
    };
    /**
     * @summary 通过父元素ID生成子元素ID，如果存在ID则不生成
     * @name uiCore#setIDByParentID
     * @param parentID 父节点ID
     * @param afterName 子元素后缀
     * @returns {fn} 子元素对象
     */
    $.fn.setIDByParentID = function (parentID, afterName) {
        var elem = this;
        if (!this instanceof jQuery) {
            elem = $(this);
        }
        if (elem.length > 0) {
            elem.attr('id', $.getIDByParentID(parentID, afterName));
        }
        return elem;
    };
    /**
     * @summary 对元素中的'ui-config'属性或者属性进行转换
     * @name uiCore#parseUIConfig
     * @methodOf 基础
     * @constructor
     * @param {Json} properties 指定要转换的元素属性
     * @returns {Jquery}
     * @example
     * target.parseUIConfig();
     * target.parseUIConfig(['id','title','width',{autoFit:'boolean',border:'boolean'},{min:'number'}]);
     */
    $.fn.parseUIConfig = function (properties) {
        var t = $(this);
        var options = {};

        var s = $.trim(t.attr('ui-config'));
        t.removeAttr('ui-config');
        if (s) {
            if (s.substring(0, 1) != '{') {
                s = '{' + s + '}';
            }
            options = (new Function('return ' + s))();
        }
        return options;
    };
    /**
     * @summary 如果组件中存在iframe，则移除iframe，回收内存，解决iframe 嵌入网页时的内存泄漏问题
     * @name uiCore#destroyIframe
     * @function
     */
    $.fn.destroyIframe = function () {
        $("iframe,frame", this).each(function () {
            try {
                if (this.contentWindow && this.contentWindow.document && this.contentWindow.close) {
                    this.contentWindow.document.write('');
                    this.contentWindow.close();
                }
                if (_IE) {
                    CollectGarbage();
                }
            } catch (ex) {
            }
        }).remove();
    };
    /**
     * @summary 控制特殊HTML组件的显示隐藏（用于遮罩问题）
     * @name uiCore#zIndexHack
     * @param {Boolean} visible
     * @param [String] excludeSelector 要排除的对象的父选择器
     * @function
     */
    $.fn.zIndexHack = function (visible, excludeSelector) {
        return this.each(function () {
            var container = $(this);

            if (_IEunder6) {
                container.find('SELECT').toggle(visible);
            }
            container.find('OBJECT,IFRAME').each(function () {
                var obj = $(this);
                if (!excludeSelector || obj.closest(excludeSelector).length == 0) {
                    if (visible) {
                        var h = parseInt(obj.attr('org_h'));
                        if (h > 0) {
                            obj.height(h);
                        } else {
                            obj.css("height", '');
                        }
                        obj.removeAttr('org_h');
                    } else {
                        if (obj.attr('org_h') == undefined) {
                            obj.attr('org_h', obj.height());
                        }
                        obj.height(0);
                    }
                }
            });
        });
    };
    /**
     * @summary 判断是否有滚动条
     * @name uiCore#hasScroll
     * @function
     * @returns {string} ''：没有 'x'：横向 'y'：纵向 'x,y'：横向+纵向
     */
    $.fn.hasScroll = function () {
        var scroll = '';
        var scroll_x = false;
        var scroll_y = false;
        var elem = this[0];
        if (elem.scrollHeight != this.height()) {
            scroll_x = true;
        }
        if (elem.scrollWidth != this.width()) {
            scroll_y = true;
        }
        if (scroll_x && scroll_y) {
            scroll = 'x,y';
        } else {
            if (!scroll_x && !scroll_y) {
                scroll = '';
            } else {
                if (scroll_x) {
                    scroll = 'x';
                }
                if (scroll_y) {
                    scroll = 'y';
                }
            }
        }
        return scroll;
    };

    /**
     * @summary 设置自适应属性, 返回父容器的width，height
     * @name uiCore#autoFit
     * @lends ui.core
     * @param fit 是否自适应
     * @param fitParent 是否适应parent，true：填充parent，false：自适应parent剩余空间
     * @param [vertical=true] 当fitParent为false时，true:垂直填充剩余空间，false：水平填充剩余空间
     * @param [filter=':visible'] 当fitParent为false时，表示当前元素兄弟的筛选器，当前元素的尺寸将设置为父容器减去兄弟元素的尺寸
     * @returns {{width: *, height: *}}
     * @private
     */
    $.fn.autoFit = function (fit, fitParent, vertical, filter) {
        var elem = this[0];
        var parent = (elem.tagName == 'BODY' ? this : this.parent());
        var fcount = parent[0].fcount === undefined ? 0 : parent[0].fcount;

        fit = fit === undefined ? true : fit;
        if (fit) {
            var pWidth = 0;
            var pHeight = 0;
            if (!elem.fitted) {
                elem.fitted = true;
                elem.fitParent = fitParent;
                parent[0].fcount = fcount + 1;
                if (parent[0].overflow == undefined) {
                    parent[0].overflow = parent.css('overflow');
                }
                parent[0].style.overflow = 'hidden';
                if (parent[0].tagName == 'BODY') {
                    $('html').addClass('autoFit');
                }
            }
            pWidth = parent.width();
            pHeight = parent.height();
            if (!fitParent) {
                var excepts = [' ui_mask ', ' ui_loading ', ' ui_dialog ', ' ui_messagebox ', ' ui_messagetip ', ' ui_tip ', ' icon_draghandler '];

                vertical = vertical === undefined ? true : vertical;
                filter = filter === undefined ? ':visible':filter;
                this.siblings(filter).each(function () {
                    var el = $(this);
                    var cls = (' ' + this.className + ' ').replace(/[\t\r\n\f]/g, ' ');
                    var flag = true;

                    for (var i = excepts.length - 1; i >= 0; i--) {
                        if (cls.indexOf(excepts[i]) >= 0) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag && this.tagName != 'SCRIPT') {
                        if (vertical) {
                            pHeight -= el.outerHeight(true);
                        } else {
                            pWidth -= el.outerWidth(true);
                        }
                    }
                });
            }
            else {
                this.css({top: 0, left: 0});
            }
            this.outerWidth(pWidth, true);
            this.outerHeight(pHeight, true);
        } else {
            if (elem.fitted) {
                elem.fitted = false;
                parent[0].fcount = fcount - 1;
                if (parent[0].fcount == 0) {
                    parent[0].style.overflow = parent[0].overflow;
                    if (parent[0].tagName == 'BODY') {
                        $('html').removeClass('autoFit');
                    }
                }
            }
        }
        return {
            width: parent.width(),
            height: parent.height()
        }
    };
    /**
     * @summary 将宽、高等属性百分比转换为px
     * @name uiCore#parseWH
     * @lends ui.core
     * @param property 属性名
     * @param value 属性值
     * @param parent Jquery类型的父容器对象
     * @param delta 边距*2
     * @returns 像素值
     * @private
     */
    $.parseWH = function (property, value, parent, delta) {
        delta = delta || 0;
        var v = $.trim(String(value || ''));
        var endchar = v.substr(v.length - 1, 1);
        if (endchar == '%') {
            v = parseInt(v.substr(0, v.length - 1));
            if (property.toLowerCase().indexOf('width') >= 0) {
                v = Math.floor((parent.width() - delta) * v / 100.0);
            } else {
                v = Math.floor((parent.height() - delta) * v / 100.0);
            }
        } else {
            v = parseInt(v) || undefined;
        }
        return v;
    };
    /**
     * @summary 通过父元素+子元素后缀获取元素对象
     * @name uiCore#getByParentID
     * @methodOf 基础
     * @constructor
     * @param parentID 父节点ID
     * @param afterName 子元素后缀
     * @returns {*|HTMLElement} 子元素对象
     */
    $.getByParentID = function (parentID, afterName, parent) {
        if (parent != null && parent != undefined) {
            return $('#' + $.getIDByParentID(parentID,afterName), parent);
        } else {
            return $('#' + $.getIDByParentID(parentID,afterName));
        }
    };
    /**
     * @summary 通过父元素ID生成子元素ID，如果存在ID则不生成
     * @name uiCore#getIDByParentID
     * @param parentID 父节点ID
     * @param afterName 子元素后缀
     * @returns {string} 生成的ID
     */
    $.getIDByParentID = function (parentID, afterName) {
        return parentID + '-' + afterName;
    };
    /**
     * @summary 在URL中添加随机参数，防止缓存
     * @name uiCore#urlAddRandom
     * @param url
     * @function
     * @returns {string}
     */
    $.urlAddRandom = function (url) {
        var rand = guidGenerator();
        var tempUrl = "";
        if (url.indexOf("?") > -1) {
            var indexRef = url.indexOf('&ref');
            if (indexRef > -1) {
                if (url.indexOf("?", indexRef) > -1) {
                    tempUrl = url + "*rand=" + rand;
                }
                else {
                    tempUrl = url + "?rand=" + rand;
                }
            }
            else {
                tempUrl = url + "&rand=" + rand;
            }
        }
        else {
            tempUrl = url + "?rand=" + rand;
        }
        return tempUrl;
    };
    var _styleSheet = null;
    /**
     * @summary 在当前文档中获取或添加全局样式
     * @name uiCore#globalCSS
     * @param selector 样式选择器
     * @param [rules] 要添加的规则
     * @param [index] 插入的索引
     * @function
     * @returns {CSSRule} 返回样式或null
     */
    $.globalCSS = function (selector, rules, index) {
        var isGet = !rules;
        index = index || 0;
        if (!_styleSheet) {
            _styleSheet = document.createElement('style');
            _styleSheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(_styleSheet);
            for (var j = 0, ss = document.styleSheets, l = ss.length; j < l; j++) {
                if (!ss[j].href) {
                    _styleSheet = ss[j];
                    break;
                }
            }
        }
        if (_styleSheet.addRule) {//IE
            var ieRules = _styleSheet.rules;
            for (var i = 0; i < ieRules.length; i++) {
                if (ieRules[i].selectorText == selector) {
                    if (isGet) {
                        return _styleSheet.rules[i];
                    }
                    _styleSheet.removeRule(selector);
                }
            }
            if (!isGet) {
                _styleSheet.addRule(selector, rules, index);
                return _styleSheet.rules[index];
            }
        }
        else if (_styleSheet.insertRule) {//firefox
            var ffRules = _styleSheet.cssRules;
            for (var k = 0; k < ffRules.length; k++) {
                if (ffRules[k].selectorText == selector) {
                    if (isGet) {
                        return _styleSheet.cssRules[k];
                    }
                    _styleSheet.deleteRule(k);
                }
            }
            if (!isGet) {
                _styleSheet.insertRule(selector + '{' + rules + '}', index);
                return _styleSheet.cssRules[index];
            }
        }
        return null;
    };
    /**
     * @summary 删除前、后的空子结点
     * @name uiCore#trimNode
     * @param [String='SE'] mode 可选值：S（删除前面的空子结点）、E（删除前面的空子结点）
     * @param [Boolean=false] deep 是否循环处理子结点
     * @returns {jQuery}
     */
    $.fn.trimNode = function (mode, deep) {
        var start, end;

        mode = (mode || 'SE').toUpperCase();
        deep = deep || false;
        start = mode.indexOf('S') !== -1;
        end = mode.indexOf('E') !== -1;
        return this.each(function () {
            var i, n, list = [];

            $(this).children().each(function () {
                var me = this;
                var flag = true;
                var node = me.firstChild;

                // 判断是否有非空结点，有非空结点时flag=false
                while (flag && node && node !== me) {
                    var t = node;
                    if (t.nodeType === 3 && !$.regexs.rx_space.test(t.data)) {
                        flag = false;
                    }
                    else if (t.nodeType === 1) {
                        node = t.firstChild;
                        if (!node) {
                            node = t.nextSibling;
                        }
                        else if (deep) {
                            $(node).trimNode(mode, deep);
                        }
                    }
                    else {
                        node = t.nextSibling;
                    }
                    while (flag && !node) {
                        node = t.parentNode;
                        if (node !== me) {
                            t = node;
                            node = node.nextSibling;
                        }
                    }
                }
                if (flag) {
                    list[list.length] = me;
                }
            });
            // 删除文档开头的空结点
            if (start) {
                for (i = 0; i < list.length; i++) {
                    n = list[i];
                    if (!n.previousSibling && n.nextSibling) {
                        n.parentNode.removeChild(n);
                        list.splice(i--, 1);
                    }
                    else {
                        break;
                    }
                }
            }
            if (end) {
                // 删除文档末尾的空结点
                for (i = list.length - 1; i >= 0; i--) {
                    n = list[i];
                    if (!n.nextSibling && n.previousSibling) {
                        n.parentNode.removeChild(n);
                        list.splice(i, 1);
                    }
                    else {
                        break;
                    }
                }
            }
        });
    };
    $.clearSelection = !window.getSelection ? function () {
        document.selection.empty();
    } : function () {
        window.getSelection().removeAllRanges();
    };
})(jQuery);
